//
//  NSObject+ky.m
//  MMTest
//
//  Created by liujianlong on 2022/9/28.
//

#import "NSObject+ky.h"

@implementation NSObject (ky)
+ (NSMutableDictionary*)getKeychainQuery:(NSString*)key
{
    return[NSMutableDictionary dictionaryWithObjectsAndKeys:
           (id)kSecClassGenericPassword,(id)kSecClass,
           key,(id)kSecAttrService,
           key,(id)kSecAttrAccount,
           (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil];
}

+ (void)save:(NSString *)key value:(nonnull id)value
{
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef) keychainQuery);
    //Add new object to searchdictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:value]forKey:(id)kSecValueData];
    //Add item to keychain with the searchdictionary
    SecItemAdd((CFDictionaryRef)keychainQuery,NULL);
}
+ (id)load:(NSString *)key
{
    id ret =nil;
    //Get search dictionary
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:key];
    //Configure the search setting
    //Since in our simple case we areexpecting only a single attribute to be returned (the password) wecan set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData =NULL;
    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery,(CFTypeRef*)&keyData) ==noErr){
        @try{
            ret =[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
        }@catch(NSException *e) {
            NSLog(@"Unarchiveof %@ failed: %@",key, e);
        }@finally{
        }
    }
    if(keyData)
        CFRelease(keyData);
    return ret;
    
}
+ (void)rm:(NSString *)key
{
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:key];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}


-(NSString *)deviceUUID
{
    // 这个key的前缀最好是你的BundleID
    NSString *bundleName = [[NSBundle mainBundle] bundleIdentifier];
    NSString*uuid = (NSString*)[NSObject load:bundleName];
    //首次执行该方法时，uuid为空
    if([uuid length] < 1)
    {
        // 获取UUID 这个是要引入<AdSupport/AdSupport.h>的
        uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        if(uuid.length == 0 || [uuid isEqualToString:@"00000000-0000-0000-0000-000000000000"])
        {
            //生成一个uuid的方法
            CFUUIDRef uuidRef= CFUUIDCreate(kCFAllocatorDefault);
            uuid = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
            CFRelease(uuidRef);
        }
        //将该uuid保存到keychain
        [NSObject save:bundleName value:uuid];
    }
    return uuid;
}
@end
